package com.globaldom.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.Gift;
import com.globaldom.model.Research;
import com.globaldom.model.UpdateTimes;
import com.globaldom.utils.Constants;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.Notifications;
import com.globaldom.utils.PMF;
import com.globaldom.utils.ResearchUtil;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/comet")
public class CometPullController {
	public CometPullController() {
	}
	private static final Logger log = Logger.getLogger(CometPullController.class.getName());

	@RequestMapping(value = "/pull", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, Object> addCivilian(HttpSession session, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		boolean updated = false;
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
			}

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			UpdateTimes update = pm.getObjectById(UpdateTimes.class, personID);
			if (null == update) {
				update = new UpdateTimes();
				update.setId(personID);
				addGifts(personID);
				updated = true;

			} else {

				Date currentTime = new Date();
				/*
				 * Research Check
				 */
				Date researchTime = update.getResearchUpdate();
				long difftime = currentTime.getTime() - researchTime.getTime();
				long diffHours = (difftime / 1000) / 3600;
				if (diffHours > 8) {
					// Update the research here

					PersistenceManager pmf = PMF.get().getPersistenceManager();
					Query query = pmf.newQuery(Research.class, "personID==pid && researchComplete==1");
					query.declareParameters("String pid");
					List<Research> myResearches = (List<Research>) query.execute(personID);
					if (myResearches.size() > 0) {
						Research research = myResearches.get(0);
						research.setResearchComplete(100); // Make changes as
						pmf.makePersistent(research);
						// per Research!!

						String ret = new ResearchUtil().updateResearch(personID, research.getResearchType().intValue());
						map.put("uresearch", ret);

						PersistenceManager npmf = PMF.get().getPersistenceManager();
						query = pmf.newQuery(Research.class,
								"personID==pid and researchComplete==2 order by researchDate ");
						query.declareParameters("String pid");
						myResearches = (List<Research>) query.execute(personID);

						if (myResearches.size() > 0) {
							Research nresearch = myResearches.get(0);
							nresearch.setResearchComplete(1);
							pmf.makePersistent(nresearch);
						}
						npmf.close();

					}

					pmf.close();
					// Put the next research in Queue
					update.setResearchUpdate(new Date());
					updated = true;
				}

				Date giftTime = update.getGiftUpdate();

				difftime = currentTime.getTime() - giftTime.getTime();
				diffHours = ((difftime / 1000) / 3600);
				if (diffHours > 24) {
					addGifts(personID);
					updated = true;
				}

			}

			List<Notifications> list = MemCacheManager.getNotifications(personID);
			if (null != list) {
				MemCacheManager.removeNotification(personID);
				map.put("notices", list);
			}

			if (updated) {
				pm.makePersistent(update);
			}
			map.put(Constants.STATUS, "+OK");

		} catch (RuntimeException rte) {
			map.put(Constants.STATUS, "+-ER");
			map.put(Constants.CODE, rte.getMessage());
			MemCacheManager.removeResearch(personID);
		} catch (Exception ex) {
			map.put(Constants.STATUS, "+-ER");
			map.put(Constants.CODE, ex.getLocalizedMessage());

		} finally {
			pm.close();

		}

		return map;
	}

	private void addGifts(String personID) {

		List<Gift> gifts = new ArrayList<Gift>();
		for (int z = 0; z < 13; z++) {
		
			Gift gift = new Gift();
			gift.setGiftType(0);
			gift.setGiftItem(z);
			gift.setGiftAmount(Math.round((((14 - z) * 100l) * Math.random())) + 10);
			gift.setGiftSender(personID);
			gifts.add(gift);
		}
		PersistenceManager pmf = PMF.get().getPersistenceManager();
		pmf.makePersistentAll(gifts);
		pmf.close();
	}

	private void removeUnclaimedGifts() {
		// TODO remove gifts that are more than 2 weeks old or more than one day
		// old and not sent to anyone!
		// Good for DB but CPU overhead. DEFER

	}

}
